package service

import (
	"github.com/vueadmin/app/admin/model"
	"github.com/vueadmin/global"
	"github.com/vueadmin/utils/conv"
)

var AdminBaseconfigService = new(adminBaseconfig)

type adminBaseconfig struct{}

/**
 * @description(配置表单)
 * @buildcode(true)
 */
func (p adminBaseconfig) Index() (map[string]interface{}, error) {
	var entity []*model.AdminBaseconfig
	if err := global.DB.Find(&entity).Error; err != nil {
		return nil, err
	}
	config := make(map[string]interface{})
	for _, val := range entity {
		config[val.Name] = val.Data
	}
	config["keyword"] = conv.StringToSlice(conv.String(config["keyword"]), ",")

	return config, nil
}

/**
 * @description(更新表单)
 * @buildcode(true)
 */
func (q adminBaseconfig) Update(req map[string]interface{}) error {
	column := make([]string, 0)
	var entity model.AdminBaseconfig
	global.DB.Model(&entity).Pluck("name", &column)

	req["keyword"] = conv.SliceToString(req["keyword"].([]interface{}))

	for key, val := range req {
		if conv.IsValueInList(key, column) {
			if err := global.DB.Model(&entity).Where("name = ?", key).Update("data", val).Error; err != nil {
				return err
			}
		} else {
			if err := global.DB.Model(&entity).Create(map[string]interface{}{"name": key, "data": val}).Error; err != nil {
				return err
			}
		}
	}
	return nil
}
